
#ifndef P2P_FLOWRATE_UTIL_HPP
#define P2P_FLOWRATE_UTIL_HPP

#include <cmath>
#include <climits>
#include "../../Timestamp.hpp"

// clockRate is the resolution and precision of clock().
static const int kClockRate = 20 * kMillisecond;


// Round returns the result of rounding t to the nearest multiple of d (since the zero time).
// The rounding behavior for halfway values is to round up.
// If d <= 0, Round returns t unchanged.
int Round(int t, int d)
{
    if(d<0) return t;
    auto x = div(t,d);
    int r=x.rem;
    if( r+r < d )
    {
        return t-r;
    }
    return t+d-r;
}

// czero is the process start time rounded down to the nearest clockRate
// increment.
int czero = Round(Timestamp::now().microSecondsSinceEpoch(), kClockRate);

// clock returns a low resolution timestamp relative to the process start time.
int64_t clock()
{
    return Round(Timestamp::now().microSecondsSinceEpoch(),kClockRate) - czero;
}

// clockToTime converts a clock() timestamp to an absolute time.Time value.
int64_t clockToTime(int64_t c) { return czero + c; }

// clockRound returns d rounded to the nearest clockRate increment.
int64_t clockRound(int64_t d) { return ( d + (kClockRate>>1))/kClockRate *kClockRate; }

// Percent represents a percentage in increments of 1/1000th of a percent.
typedef int32_t Percent;

// percentOf calculates what percent of the total is x.
Percent percentOf(double x, double total)
{
    if(x<0 || total<0) return 0;
    else if(int p = round(x/total * 1e5) <= INT32_MAX) return Percent(p);
    return Percent(INT32_MAX);
}

double Float(Percent p){ return double(p) * 1e-3; }


#endif // !P2P_FLOWRATE_UTIL_HPP